package com.nanjia.boot.delivery.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.delivery.converter.InvoiceConverter;
import com.nanjia.boot.delivery.mapper.InvoiceMapper;
import com.nanjia.boot.delivery.model.entity.Invoice;
import com.nanjia.boot.delivery.model.form.InvoiceForm;
import com.nanjia.boot.delivery.model.query.InvoiceQuery;
import com.nanjia.boot.delivery.model.vo.InvoiceVO;
import com.nanjia.boot.delivery.service.InvoiceService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 发票管理服务实现类
 *
 * @author 周洋
 * @since 2025-06-13 10:55
 */
@Service
@RequiredArgsConstructor
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper, Invoice> implements InvoiceService {

    private final InvoiceConverter invoiceConverter;

    /**
     * 获取发票管理分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<InvoiceVO>} 发票管理分页列表
     */
    @Override
    public IPage<InvoiceVO> getInvoicePage(InvoiceQuery queryParams) {
        return this.baseMapper.getInvoicePage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
    }

    /**
     * 获取发票管理表单数据
     *
     * @param id 发票管理ID
     * @return 发票管理表单数据
     */
    @Override
    public InvoiceForm getInvoiceFormData(Long id) {
        Invoice entity = this.getById(id);
        return invoiceConverter.toForm(entity);
    }

    /**
     * 新增发票管理
     *
     * @param formData 发票管理表单对象
     * @param ipAddr   ip
     * @return 是否新增成功
     */
    @Override
    public boolean saveInvoice(InvoiceForm formData, String ipAddr) {
        if (formData.getInvoiceDefault() != null && formData.getInvoiceDefault() == 1) {

            List<Invoice> invoiceList = this.list(Wrappers.<Invoice>lambdaQuery().eq(Invoice::getInvoiceTypeCode, formData.getInvoiceTypeCode())
                    .eq(Invoice::getSubdomainCode, SecurityUtils.getSubdomainCode())
                    .eq(Invoice::getSubdomainUserCode, SecurityUtils.getUserCode())
                    .orderByDesc(Invoice::getId));
            if (CollectionUtils.isNotEmpty(invoiceList)) {
                for (Invoice invoice : invoiceList) {
                    invoice.setInvoiceDefault(0);
                }
                this.updateBatchById(invoiceList, invoiceList.size());
            }

        }
        LambdaQueryWrapper<Invoice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Invoice::getId);
        List<Invoice> list = this.list(queryWrapper);
        int x = 0;
        if (CollectionUtils.isNotEmpty(list)) {
            x = Integer.parseInt(list.get(0).getInvoiceCode());
        }
        Invoice entity = invoiceConverter.toEntity(formData);
        entity.setSubdomainCode(SecurityUtils.getSubdomainCode());
        entity.setSubdomainUserCode(SecurityUtils.getUserCode());
        entity.setInvoiceCode(String.format("%04d", x + 1));
        entity.setCreateBy(SecurityUtils.getUserStrId());
        entity.setCreateIp(ipAddr);
        entity.setCreateTime(LocalDateTime.now());
        entity.setInvoiceStatus(StatusEnum.ENABLE.getValue());
        return this.save(entity);
    }

    /**
     * 更新发票管理
     *
     * @param id       发票管理ID
     * @param formData 发票管理表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateInvoice(Long id, InvoiceForm formData) {
        if (formData.getInvoiceDefault() != null && formData.getInvoiceDefault() == 1) {
            Invoice byId = this.getById(id);
            if (byId.getInvoiceDefault().intValue() != 1) {
                List<Invoice> invoiceList = this.list(Wrappers.<Invoice>lambdaQuery().eq(Invoice::getInvoiceTypeCode, byId.getInvoiceTypeCode())
                        .eq(Invoice::getSubdomainCode, byId.getSubdomainCode())
                        .eq(Invoice::getSubdomainUserCode, byId.getSubdomainUserCode())
                        .ne(Invoice::getId, byId.getId())
                        .orderByDesc(Invoice::getId));
                if (CollectionUtils.isNotEmpty(invoiceList)) {
                    for (Invoice invoice : invoiceList) {
                        invoice.setInvoiceDefault(0);
                    }
                    this.updateBatchById(invoiceList, invoiceList.size());
                }
            }
        }
        Invoice entity = invoiceConverter.toEntity(formData);
        entity.setSubdomainCode(null);
        entity.setSubdomainUserCode(null);
        entity.setId(id);
        return this.updateById(entity);
    }

    /**
     * 删除发票管理
     *
     * @param ids 发票管理ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteInvoices(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的发票管理数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        List<Invoice> list = new ArrayList<>();
        for (Long l : idList) {
            Invoice invoice = new Invoice();
            invoice.setId(l);
            invoice.setUpdateTime(LocalDateTime.now());
            invoice.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
            invoice.setInvoiceStatus(StatusEnum.DELETE.getValue());
            list.add(invoice);
        }
        return this.updateBatchById(list, idList.size());
    }

}
